package com.djq.hhc.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.djq.hhc.dataprocess.ImgLoadUtils;
import com.djq.hhc.dto.PostTypeDto;
import com.djq.hhc.feign.CreditInfoFeignClient;
import com.djq.hhc.dto.UserInfoDto;
import com.djq.hhc.holder.UserHolder;
import com.djq.hhc.model.credit.CreditInfo;
import com.djq.hhc.model.post.PostType;
import com.djq.hhc.model.user.UserInfo;

import com.djq.hhc.result.Result;
import com.djq.hhc.service.UserInfoService;
import com.djq.hhc.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/02/25/下午 8:41
 * @Description:
 */

@RestController
@RequestMapping(value = "/user/userInfo")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    //跟据Set<String>获取对应的List<UserDto>
    @GetMapping("getDtosBySet")
    public Result getDtosBySet(@RequestHeader("Authorization") String token, @RequestParam("tops") Set<String> top5) {
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        List<UserInfoDto> userInfoDtos = userInfoService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + idStr + ")")
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserInfoDto.class))
                .collect(Collectors.toList());
        return Result.ok(userInfoDtos);
    }

    //返回所有用户
    @GetMapping("/getAllUser")
    public Result getAllUser() {
        List<UserInfo> list = userInfoService.list();
        List<UserInfoDto> res = list.stream()
                .map(userInfo -> new UserInfoDto(userInfo.getId(), userInfo.getNickName(), userInfo.getAvatar()))
                .collect(Collectors.toList());
        return Result.ok(res);
    }

    //获取当前用户+积分
    @GetMapping("getNowUserWithCredit")
    public Result getNowUserWithCredit(@RequestHeader("Authorization") String token) {
        return userInfoService.getNowUserWithCredit(token);
    }

    //当前登录的用户修改自己的信息，这个用户不能更改自己的积分，所以就不用远程调用feign了
    @PutMapping("updateNowUser")
    public Result updateNowUser(@RequestHeader("Authorization") String token, @RequestBody UserInfo userInfo) {
        return userInfoService.updateNowUser(token, userInfo);
    }

    //退出
    @PostMapping("logout")
    public Result logout(@RequestHeader("Authorization") String token) {
        return userInfoService.logoutByToken(token);
    }

    //查询所有用户
    @GetMapping("findAll")
    public Result findAll() {
        List<UserInfo> userInfos = userInfoService.list();
        return Result.ok(userInfos).message("成功：查询所有用户");
    }

    //新增用户
    @PostMapping("save")
    public Result save(@RequestBody UserInfo userInfo) {
        userInfoService.save(userInfo);
        return Result.ok(null);
    }

    //通过id获取用户
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        UserInfo userInfo = userInfoService.getById(id);
        return Result.ok(userInfo);
    }

    //修改
    @PutMapping("update")
    public Result updateById(@RequestBody UserInfo userInfo) {
        return userInfoService.updateUserById(userInfo);
    }

    //删除用户
    @DeleteMapping("remove/{id}")
    public Result removeById(@PathVariable Integer id) {
        Boolean isOk = userInfoService.removeById(id);
        if (isOk) {
            return Result.ok(null).message("删除用户成功");
        } else {
            return Result.fail(null).message("删除用户失败");
        }
    }

    //批量删除
    @DeleteMapping("batchRemove")
    public Result batchRemove(@RequestBody List<Long> idList) {
        userInfoService.removeByIds(idList);
        return Result.ok(null);
    }

    //发送短信
    @PostMapping("sendMail/{mail}")
    public Result sendMail(@PathVariable String mail) {
        return userInfoService.sendMail(mail);
    }

    //检验登录
    @PostMapping("/loginVerification")
    public Result loginVerification(@RequestBody Map map) {
        //1、调用map集合获取请求参数
        String email = (String) map.get("email");
        String code = (String) map.get("verificationCode");
        //2、调用userService完成用户登录
        return userInfoService.loginVerification(email,code);
    }

    //获取登录用户
    @GetMapping("getLoginUser")
    public Result getLoginUser() {
        UserInfoDto user = UserHolder.getUser();
        if (user != null) {
            return Result.ok(user);
        } else {
            return Result.fail();
        }
    }



    //分页
    @PostMapping("{page}/{limit}")
    public Result index(
            @PathVariable Long page,
            @PathVariable Long limit,
            @RequestBody(required = false) UserInfoVo userInfoVo) {
        UserInfoDto user = UserHolder.getUser();
        if (user == null) {
            return Result.fail().message("请先登录");
        }
        if (user.getLimits() == 0) {
            return Result.fail().message("你不是管理员");
        }
        //创建page对象，传递当前页和每页记录数
        //System.out.println(userInfoVo.toString());
        Page<UserInfo> pageParam = new Page<>(page, limit);
        //获取条件值
        String name = userInfoVo.getName();//用户昵称
        Integer sex = userInfoVo.getSex();//用户性别
        String email = userInfoVo.getEmail();//用户邮箱
        String hhid = userInfoVo.getHhid();//用户花花id
        Integer limits = userInfoVo.getLimits(); //权限
        //封装条件
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("nick_name",name);
        }
        if(!StringUtils.isEmpty(sex)) {
            wrapper.eq("sex",sex);
        }
        if(!StringUtils.isEmpty(limits)) {
            wrapper.eq("limits",limits);
        }
        if(!StringUtils.isEmpty(email)) {
            wrapper.like("email",email);
        }
        if(!StringUtils.isEmpty(hhid)) {
            wrapper.like("hhid",hhid);
        }
        //调用方法得到分页查询结果
        IPage<UserInfo> pageModel = userInfoService.page(pageParam, wrapper);
        return Result.ok(pageModel);
    }

    /**
     * 下载图片
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        String s = ImgLoadUtils.upLoad(file);
        return Result.ok(s);
    }

    /**
     * 下载图片
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        ImgLoadUtils.downLoad(name, response);
    }
}
